# coding: utf-8
import os
from datetime import datetime
import allure
from config.GlobalVar import G
from handler.LoggerHandler import logger
from selenium.webdriver.common.by import By
from appium import webdriver


class BasePage:
    # 浮动元素、广告元素黑名单
    black_list = [
        # 格式：(By.ID, "edu.yjyx.student:id/et_name")
    ]
    max = 0

    # 声明driver是webdriver.Remote类型
    def __init__(self, driver: webdriver.Remote):
        self.driver = driver
        self.log = logger()

    def find_element(self, *loc):
        # 自定义的find_element方法
        # 处理弹框 异常处理 动态浮动的元素的处理
        try:
            # 找到了就返回元素
            return self.driver.find_element(*loc)
        except Exception as e:
            # 三次查找失败，抛出异常
            if self.max > 3:
                self.log.error(str(e))
                raise e
            self.max = self.max + 1
            for black_element in self.black_list:
                elements = self.driver.find_elements(*black_element)
                # 如果找到了黑名单元素，那么就点击它
                if len(elements) >= 1:
                    elements[0].click()
            # 递归，返回继续查找
            return self.find_element(*loc)

    def get_window_size(self):
        return self.driver.get_window_size()

    def swipe(self, start_x, start_y, end_x, end_y, duration):
        return self.driver.swipe(start_x, start_y, end_x, end_y, duration)

    # 左滑屏幕
    def swipe_left(self, time=500):
        size = self.get_window_size()
        self.swipe(size["width"] * 0.9, size["height"] / 2, size["width"] * 0.1, size["height"] / 2, time)

    # 右滑屏幕
    def swipe_right(self, time=500):
        size = self.get_window_size()
        self.swipe(size["width"] * 0.1, size["height"] / 2, size["width"] * 0.9, size["height"] / 2, time)

    # 上滑屏幕
    def swipe_up(self, time=500):
        size = self.get_window_size()
        self.swipe(size["width"] / 2, size["height"] * 0.9, size["width"] / 2, size["height"] * 0.1, time)

    # 下滑屏幕
    def swipe_down(self, time=500):
        size = self.get_window_size()
        self.swipe(size["width"] / 2, size["height"] * 0.1, size["width"] / 2, size["height"] * 0.9, time)

    # 寻找Toast消息框
    def find_toast(self, toast_message):
        message = (By.XPATH, '//*[@text=\'{}\']'.format(toast_message))
        self.find_element(*message)

    # 屏幕截图
    def save_screenshot(self, describe):
        if not os.path.exists(G.SCREENSHOT_DIR):
            os.mkdir(G.SCREENSHOT_DIR)
        file_name = G.SCREENSHOT_DIR + "\\{}_{}.png".format(datetime.strftime(datetime.now(), "%Y%m%d%H%M%S"), describe)
        self.driver.save_screenshot(file_name)
        with open(file_name, mode='rb') as f:
            file = f.read()
        allure.attach(file, describe, allure.attachment_type.PNG)
        log = logger()
        log.info("截图文件保存在：{}".format(file_name))
